﻿using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace KingdeePdaService
{
    /// <summary>
    /// PdaService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class PdaService : System.Web.Services.WebService
    {
        /// <summary>
        /// 获取数据中心
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public DataSet GetAccounts()
        {
            return ConfigDatas.KingdeeAccounts;
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="accountId">账套</param>
        /// <param name="userid">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="localid">中文 2052</param>
        /// <returns></returns>
        [WebMethod]
        public DataSet Login(string accountId, string userid, string password, int localid){
            
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);
            JObject obj;
            DataSet results= Login(client,accountId, userid, password, localid,out obj);
            if (results == null) return null;
            
            return results;

        }

        public static DataSet Login(K3CloudApiClient client ,string accountId, string userid, string password, int localid,out JObject obj)
        {

        
            
            string ret = client.ValidateLogin(accountId, userid, password, localid);
             obj = JObject.Parse(ret);
            var result = obj["LoginResultType"].Value<int>();
            // 登陆成功
            if (result == 1)
            {
                DataSet loginMsg = new DataSet();
                // 取用户的组织ID和用户的ID ，记录到table中； 
                
                // client.("5a460d781d9047", "Administrator", "888888", 2052);
                string orgId =Convert.ToString( obj["Context"]["CurrentOrganizationInfo"]["ID"] );         //组织Id
                string orgName = Convert.ToString(obj["Context"]["CurrentOrganizationInfo"]["Name"]);    //组织名
                string userId = Convert.ToString(obj["Context"]["UserId"]);                             //用户Id
                string userName = Convert.ToString(obj["Context"]["UserName"]);                         //用户名     
                Type ty = typeof(string);
                DataTable table = new DataTable();
                table.Columns.Add("OrgId", ty);
                table.Columns.Add("OrgName", ty);
                table.Columns.Add("UserId", ty);
                table.Columns.Add("UserName", ty);
                DataRow row = table.NewRow();
                row["OrgId"] = orgId;
                row["OrgName"] = orgName;
                row["UserId"] = userid;
                row["UserName"] = userName;
                table.Rows.Add(row);
                loginMsg.Tables.Add(table);
                return loginMsg;
            }
            return null;
        }


        /// <summary>
        ///  获取条码内容
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="localid"></param>
        /// <param name="orgId">组织Id</param>
        /// <param name="stockId">仓库Id</param>
        /// <param name="codes">条码，逗号分隔</param>
        /// <param name="isbool">是否过滤库存数大于0</param>
        /// <returns></returns>
        [WebMethod]
        public DataSet GetCodeDetail(string accountId, string userid, string password, int localid,string codes ,string orgId ,string stockId ,bool isbool)
        {
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);
           
            JObject obj;
            if (Login(client,accountId, userid, password, localid,out obj)==null){
                return null;
            }
            string[] cs = codes.Split(new string[1] { "," }, StringSplitOptions.RemoveEmptyEntries);
            System.Text.StringBuilder sbd = new System.Text.StringBuilder();
            foreach (string s in cs) {
                sbd.Append("'");
                sbd.Append(s.Trim());
                sbd.Append("',");
                  
            }
            //条码主档   中，根据条码获取的。 
            //FormId 表单标识
            //FieldKeys 要获取的字段的标识 用,隔开
            //FilterString 过滤字符串 
            string formId = "BD_BarCodeMainFile";
            //                       0  物料编码      1   物料名    2  条码   3 库存数量  4 计量单位   5 幅宽         6 密度               7 生产备料单Id          8 生产备料单分录Id        9关联对外材质
            string fieldKeys = "FMaterialId.FNumber,FMaterialId.FName,FBarCode,F_StockQty,FUnitId.FNumber,FAuxPropId,FMaterialId.FDensity,FManufactureStockId,FManufactureStockEntryId   ,FOutMaterialNum.FNumber";
            string stockQtyStr = " ";
            if (isbool) stockQtyStr = " and F_StockQty>0 ";
            string filter = string.Format(
                "FBarCode='{0}' and FForbidStatus='A' and FStockOrgId='{1}' and FStockId='{2}'  {3}",
                codes, orgId, stockId ,stockQtyStr
                );
            string str = string.Format(
                "\"FormId\":\"{0}\",\"FieldKeys\":\"{1}\",\"FilterString\":\"{2}\",\"OrderString\":\"FID ASC\",\"TopRowCount\":\"0\",\"StartRow\":\"0\",\"Limit\":\"1999\"",
                formId, fieldKeys, filter
                );
            str = "{" + str + "}";
            List<List<object>> datas = client.ExecuteBillQuery(str);
            if (datas == null || datas.Count == 0) return null;
            DataSet dst = new DataSet();
            DataTable tabl = new DataTable();
            Type tp = typeof(string);
            tabl.Columns.Add(new DataColumn("FMaterialId", tp));               //物料编码
            tabl.Columns.Add(new DataColumn("FMaterialFName", tp));             //物料名
            tabl.Columns.Add(new DataColumn("FBarCode", tp));                   //条码
            tabl.Columns.Add(new DataColumn("FBaseQty", tp));                   //库存数量               备注   后期改成  库存数量     字段名不变
            tabl.Columns.Add(new DataColumn("FBaseUnitId", tp));                //基础单位
            tabl.Columns.Add(new DataColumn("FAuxPropId", tp));                 //幅宽
            tabl.Columns.Add(new DataColumn("AuxpropValue", tp));                //幅宽值
            tabl.Columns.Add(new DataColumn("FDiameter", tp));                  //芯径
            tabl.Columns.Add(new DataColumn("FDensity", tp));                   //密度
            tabl.Columns.Add(new DataColumn("FManufactureStockId", tp));                   //生产备料单Id
            tabl.Columns.Add(new DataColumn("FManufactureStockEntryId", tp));                   //密度生产备料单分录Id
            //tabl.Columns.Add(new DataColumn("FIsForOut", tp));                   //是否对外材质
            tabl.Columns.Add(new DataColumn("FOutMaterialNum", tp));              //对外材质编码

            DataRow dicData = tabl.NewRow();
            foreach (var data in datas)
            {
                //  物料编码         物料名        条码       库存数量    计量单位         幅宽      幅宽值         芯径         密度
                //FMaterialId,  FMaterialId.Name, FBarCode,  F_StockQty,  FBaseUnitId,    FAuxPropId ,AuxpropValue  ,FDiameter  ， FDensity ,         
                dicData["FMaterialId"] = Convert.ToString( data[0]);
                dicData["FMaterialFName"] = Convert.ToString(data[1]);
                dicData["FBarCode"] = Convert.ToString(data[2]);
                dicData["FBaseQty"] = Convert.ToString(data[3]);
                dicData["FBaseUnitId"] = Convert.ToString(data[4]);

                List<List<object>> fkList = GetFK(Convert.ToString(data[5]), client);
                foreach(var fk in fkList)
                {
                    dicData["FAuxPropId"]=fk[0];
                    dicData["AuxpropValue"] = fk[1];
                }

                dicData["FDiameter"] = Convert.ToString(FDiameter());
                
                dicData["FDensity"] =Convert.ToString(data[6]);

                dicData["FManufactureStockId"] = Convert.ToString(data[7]);
                dicData["FManufactureStockEntryId"] = Convert.ToString(data[8]);

                dicData["FOutMaterialNum"] = Convert.ToString(data[9]);

                tabl.Rows.Add(dicData);
                break;
            }
            dst.Tables.Add(tabl);
            
            return dst;
            //return ConfigDatas.KingdeeAccounts;
        }
        /// <summary>
        /// 芯径(半径)固定值（MM）
        /// 3英寸
        /// </summary>
        /// <returns></returns>
        public decimal FDiameter()
        {
            return 76.2M;
        }
        /// <summary>
        /// 幅宽查询
        /// </summary>
        /// <param name="auxPropId"></param>
        /// <param name="client"></param>
        /// <returns></returns>
        public List<List<object>>  GetFK(string auxPropId, K3CloudApiClient client)
        {
            string formId = "kf454abc5de8f450b9f47f270cff57832";      //幅宽视唯一标识
            string fieldKeys = "FNUMBER,FDATAVALUE";
            string filter = string.Format(
                "FID='{0}'",
                auxPropId
                );
            string str = string.Format(
                "\"FormId\":\"{0}\",\"FieldKeys\":\"{1}\",\"FilterString\":\"{2}\",\"OrderString\":\"FID ASC\",\"TopRowCount\":\"0\",\"StartRow\":\"0\",\"Limit\":\"1999\"",
                formId, fieldKeys, filter
                );
            List<List<object>> datas = client.ExecuteBillQuery("{" + str + "}");
            return datas;
        }
        
        /// <summary>
        /// 获取组织，仓库
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="localid"></param>
        /// <returns></returns>
        [WebMethod]
        public DataSet GetOrgStock(string accountId, string userid, string password, int localid)
        {
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);
            PDADictionary<string, string> msg = new PDADictionary<string, string>();
            JObject obj;
            if (Login(client, accountId, userid, password, localid, out obj)==null)
            {
                return null;
            }


            //仓库  
            //FormId 表单标识
            //FieldKeys 要获取的字段的标识 用,隔开
            //FilterString 过滤字符串 
            string formId = "BD_STOCK";
            //                 使用组织Id    使用组织编号      使用组织名    仓库Id  仓库名 仓库编码 
            string fieldKeys = "FUseOrgId,FUseOrgId.FNumber,FUseOrgId.FName,FStockId,FName,FNumber";
            string filter = "FDocumentStatus='c' and FDefStockStatusId=10000";
            string str = string.Format(
                "\"FormId\":\"{0}\",\"FieldKeys\":\"{1}\",\"FilterString\":\"{2}\",\"OrderString\":\"FstockId ASC\",\"TopRowCount\":\"0\",\"StartRow\":\"0\",\"Limit\":\"1999\"",
                formId, fieldKeys, filter
                );
            List<List<object>> datas = client.ExecuteBillQuery("{" + str + "}");
            if (datas.Count == 0 || datas == null) return null;
            Type ty = typeof(string);
            DataSet set = new DataSet();
            DataTable table = new DataTable();
            table.Columns.Add("FUseOrgId", ty);
            table.Columns.Add("OrgFNumber", ty);
            table.Columns.Add("OrgFName", ty);
            table.Columns.Add("StockId", ty);
            table.Columns.Add("StockFName", ty);
            table.Columns.Add("StockFNumber", ty);
            DataRow row = table.NewRow();
            foreach (var data in datas)
            {
                row = table.NewRow();
                //  组织Id     组织编码    组织名      仓库Id    仓库名  仓库编码 
                //FUseOrgId  ,OrgFNumber , OrgFName ,  FStockId  ， FName,  FNumber
                row["FUseOrgId"] = Convert.ToString(data[0]);
                row["OrgFNumber"] = Convert.ToString(data[1]);
                row["OrgFName"] = Convert.ToString(data[2]);
                row["StockId"] = Convert.ToString(data[3]);
                row["StockFName"] = Convert.ToString(data[4]);
                row["StockFNumber"] = Convert.ToString(data[5]);
                table.Rows.Add(row);
            }
            set.Tables.Add(table);
            return set;
            
        }


        /// <summary>
        /// 根据编号获取  销售订单
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="billNo"></param>
        /// <returns></returns>
        [WebMethod]
        public DataSet GetSaleOrder(string accountId, string userid, string password, int localid, string billNo, string orgId)
        {
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);

            JObject obj;
            if (Login(client, accountId, userid, password, localid, out obj) == null)
            {
                return null;
            }

            string billName = "SAL_SaleOrder";      //单据名
            var billStr = client.View(billName, "{\"CreateOrgId\":\"0\",\"Number\":\"" + billNo + "\",\"Id\":\"\"}");

            string billType = "XSDD01_SYS";  //单据类型  标准销售订单
            JObject jo = (JObject)JsonConvert.DeserializeObject(billStr);
            string str = Convert.ToString(jo["Result"]["ResponseStatus"]);

            if ((str == "" || str == null) && Convert.ToString(jo["Result"]["Result"]["BillTypeId"]["Number"]) == billType && Convert.ToString(jo["Result"]["Result"]["DocumentStatus"]) == "C" && Convert.ToString(jo["Result"]["Result"]["SaleOrgId_Id"]) == orgId)
            {
                Type type = typeof(string);
                DataSet ds = new DataSet();
                //单据头
                DataTable table = new DataTable();
                //销售订单Id
                table.Columns.Add("Id", type);
                //销售组织
                table.Columns.Add("FSaleOrgId", type);


                //单据体
                DataTable subTable = new DataTable();
                //单据体Id
                subTable.Columns.Add("Id", type);
                //物料编码
                subTable.Columns.Add("FMaterialNum", type);
                //物料名称
                subTable.Columns.Add("FMaterialName", type);
                //幅宽编码
                subTable.Columns.Add("FAuxPropId", type);
                //幅宽名称
                subTable.Columns.Add("FAuxPropName", type);
                //单位
                subTable.Columns.Add("FUnitName", type);



                //销售数量
                subTable.Columns.Add("FQty", type);
                //基本单位
                subTable.Columns.Add("FBaseUnitId", type);
                //可出数量（库存基本）
                subTable.Columns.Add("FStockBaseCanOutQty", type);


                //单据头赋值
                DataRow row = table.NewRow();
                //Id
                row["Id"] = jo["Result"]["Result"]["Id"];
                //组织
                row["FSaleOrgId"] = jo["Result"]["Result"]["SaleOrgId_Id"];

                table.Rows.Add(row);
                //单据体
                foreach (var entity in jo["Result"]["Result"]["SaleOrderEntry"])
                {
                    string a = entity.ToString();
                    DataRow subRow = subTable.NewRow();
                    //id
                    subRow["Id"] = entity["Id"];
                    //物料编码
                    subRow["FMaterialNum"] = entity["MaterialId"]["Number"];
                    //物料名称
                    subRow["FMaterialName"] = entity["MaterialId"]["Name"][0]["Value"];
                    //幅宽
                    subRow["FAuxPropId"] = entity["AuxPropId"]["F100001"]["FNumber"];
                    subRow["FAuxPropName"] = entity["AuxPropId"]["F100001"]["FDataValue"][0]["Value"];
                    //销售单位
                    subRow["FUnitName"]=entity["UnitId"]["Name"][0]["Value"];

                    //销售数量
                    subRow["FQty"] = entity["Qty"];
                    //基本单位
                    subRow["FBaseUnitId"] = entity["BaseUnitId"]["Name"][0]["Value"];
                    //可出数量
                    subRow["FStockBaseCanOutQty"] = entity["StockBaseCanOutQty"];
                    subTable.Rows.Add(subRow);
                }
                
                ds.Tables.Add(table);
                ds.Tables.Add(subTable);


                return ds;
            }
            return null;
        }
        /// <summary>
        /// 销售出库单（不发布）保存
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="localid"></param>
        /// <param name="FPkValue">生产备料单主键</param>
        /// <param name="dataS">单据体</param>
        /// <param name="onlyMark">单据唯一标识</param>
        /// <returns></returns>
        [WebMethod]
        public string SaleOutStock(string accountId, string userid, string password, int localid, string FPkValue, string orgId, string outStock, DataSet dataS, string onlyMark)
        {
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);
            PDADictionary<string, string> msg = new PDADictionary<string, string>();
            JObject obj = null;
            if (Login(client, accountId, userid, password, localid, out obj) == null || FPkValue == null || FPkValue == "" || dataS == null || dataS.Tables.Count == 0)
            {
                return null;
            }
            string userId = Convert.ToString(obj["Context"]["CurrentOrganizationInfo"]["ID"]);               //从obj直接获取用户Id





            DataTable table = dataS.Tables[0];
            System.Text.StringBuilder sbd = new System.Text.StringBuilder();

            sbd.Append("{\"Creator\":\"" + userId + "\",");
            sbd.Append("\"NeedUpDateFields\":[],");
            sbd.Append("\"NeedReturnFields\":[],");
            sbd.Append("\"IsDeleteEntry\":\"True\",");
            sbd.Append("\"SubSystemId\":\"\",");
            sbd.Append("\"IsVerifyBaseDataField\":\"false\",");
            sbd.Append("\"IsEntryBatchFill\":\"True\",");
            sbd.Append("\"Model\":{\"FID\":\"0\",");
            sbd.Append("\"FBillNo\":\"\",");
            sbd.Append("\"FModifierId\":{\"FUserID\":\"0\"},");
            sbd.Append("\"FModifyDate\":\"1900-01-01\",");
            sbd.Append("\"FCreatorId\":{\"FUserID\":\"0\"},");
            sbd.Append("\"FCreateDate\":\"1900-01-01\",");
            sbd.Append("\"FApproverId\":{\"FUserID\":\"0\"},");
            sbd.Append("\"FApproveDate\":\"1900-01-01\",");
            sbd.Append("\"FOrgId\":{\"FNumber\":\""+ orgId + "\"},");
            sbd.Append("\"FPkValue\":\"" + FPkValue + "\",");
            sbd.Append("\"FStockId\":{\"FNumber\":\"" + outStock + "\"},");
            sbd.Append("\"FEntity\":[");

            int i = dataS.Tables[0].Rows.Count;
            foreach (DataRow dr in dataS.Tables[0].Rows)
            {
                i--;
                sbd.Append("{\"FEntryID\":\"0\",");
                sbd.Append("\"FEntryEntityPkvalues\":\"" + dr["Id"] + "\",");
                sbd.Append("\"FBarCode\":\"" + dr["FBarCode"] + "\",");
                sbd.Append("\"FMaterialId\":{\"FNumber\":\"" + dr["FMaterialId"] + "\"},");
                sbd.Append("\"FAuxPropId\":{\"FAUXPROPID__FF100001\":{\"FNumber\":\"" + dr["FAuxPropId"] + "\"}},");
                sbd.Append("\"FBaseUnitId\":{\"FNumber\":\"" + dr["UnitId"] + "\"},");
                sbd.Append("\"FBaseQty\":\"" + dr["Qty"] + "\",");
                sbd.Append("\"FTargetFormId\":\"\"");
                sbd.Append("}");
                if (i > 0)
                    sbd.Append(",");
            }
            sbd.Append("]}}");
            // k92815848ca6048b7a0e2a5b28c171573   销售订单到销售出库（中间单） 唯一标识
            //if (onlyMark == null)
            //    onlyMark = "k92815848ca6048b7a0e2a5b28c171573";
            
            string resultSave = client.Save(onlyMark, sbd.ToString());          //保存
            //string resultSubmit = client.Submit("STK_TransferDirect", a1);               //提交
            //string resultAudit = client.Audit("STK_TransferDirect", a1);                 //审核
            JObject jo = (JObject)JsonConvert.DeserializeObject(resultSave);
            string isSuccess = jo["Result"]["ResponseStatus"]["IsSuccess"].ToString();
            if (isSuccess == "True")
            {
                return "保存成功";
            }

            string rs=Convert.ToString(jo["Result"]["ResponseStatus"]);
            if (rs!=null&&rs!="")
            {
                rs = Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"]);
                if(rs!=null&&rs!="")
                {
                    isSuccess += Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"][0]["FieldName"]);
                }
            }
            return "保存失败：" + isSuccess;

        }
        /// <summary>
        /// 根据编号获取  生产备料单
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="billNo"></param>
        /// <returns></returns>
        [WebMethod]
        public DataSet ManufactureStock(string accountId ,string userid,string password,int localid, string billNo,string orgId ,string outStockId)
        {
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);

            JObject obj;
            if (Login(client, accountId, userid, password, localid, out obj) == null)
            {
                return null;
            }

            string billName = "UN_ManufactureStock";      //单据名
            var billStr = client.View(billName, "{\"CreateOrgId\":\"0\",\"Number\":\"" + billNo + "\",\"Id\":\"\"}");
            
            JObject jo = (JObject)JsonConvert.DeserializeObject(billStr);
            string aoo = Convert.ToString(jo);
            string str = Convert.ToString(jo["Result"]["ResponseStatus"]);
            //&& Convert.ToString(jo["Result"]["Result"]["FBillTypeID"]["Number"])== "SCBLD001_SYS"
            if ((str == "" || str == null ) &&  Convert.ToString(jo["Result"]["Result"]["DocumentStatus"])=="C" && Convert.ToString(jo["Result"]["Result"]["FOrgId_Id"]) == orgId)
            {
                if (outStockId != Convert.ToString(jo["Result"]["Result"]["FOutDepositoryId_Id"]))
                    return null;
                Type type = typeof(string);
                DataSet ds = new DataSet();
                //单据头
                DataTable table = new DataTable();
                //生产备料单Id
                table.Columns.Add("Id", type);
                //生产组织(即 库存组织)
                table.Columns.Add("FOrgId", type);
                //调出仓库 
                table.Columns.Add("FOutDepositoryId", type);
                

                //单据体
                DataTable subTable = new DataTable();
                //单据体Id
                subTable.Columns.Add("Id", type);
                //物料编码
                subTable.Columns.Add("FRawMaterialNum", type);
                //物料名称
                subTable.Columns.Add("FMaterialName", type);
                //幅宽编码
                subTable.Columns.Add("FAuxPropertyId", type);
                //幅宽名称
                subTable.Columns.Add("FAuxPropertyName", type);
                //调入仓库编码
                subTable.Columns.Add("FInDepositoryId", type);
                //调入仓库名称
                subTable.Columns.Add("FInDepositoryName", type);
                //预计需求量
                subTable.Columns.Add("FPlanDosage", type);
                //实际领料量
                subTable.Columns.Add("FActuralDosage", type);
                //生产机组
                subTable.Columns.Add("FMachine", type);
                //锁定材质
                subTable.Columns.Add("FLockMaterial", type);
                //是否对外材质
                subTable.Columns.Add("FIsForOut", type);
                //关联对外材质编码
                subTable.Columns.Add("FOutMaterialNum", type);
                
                //单据头赋值
                DataRow row = table.NewRow();
                //Id
                row["Id"] = jo["Result"]["Result"]["Id"];
                //组织
                row["FOrgId"] = jo["Result"]["Result"]["FOrgId_Id"];
                //调出仓库
                row["FOutDepositoryId"] = jo["Result"]["Result"]["FOutDepositoryId_Id"];

                table.Rows.Add(row);
                //单据体
                foreach (var entity in jo["Result"]["Result"]["FEntity"])
                {
                    string a = entity.ToString();
                    DataRow subRow = subTable.NewRow();
                    //id
                    subRow["Id"] = entity["Id"];
                    //物料编码
                    subRow["FRawMaterialNum"] = entity["FRawMaterialId"]["Number"];
                    //物料名称
                    subRow["FMaterialName"] = entity["FRawMaterialId"]["Name"][0]["Value"];
                    //是否对外材质
                    subRow["FIsForOut"] = entity["FRawMaterialId"]["Raw_Material"][0]["FISFOROUT"];
                    subRow["FLockMaterial"] = entity["FLockMaterial"];
                    //关联对外材质编码
                    if(Convert.ToString(entity["FRawMaterialId"]["Raw_Material"][0]["FISFOROUT"])=="False")
                    {
                        subRow["FOutMaterialNum"] = entity["FRawMaterialId"]["Raw_Material"][0]["F_PAEZ_Base"]["Number"];
                    }

                    //生产机组
                    subRow["FMachine"] = entity["FMachine"];
                    //幅宽，如果备料单没有幅宽，那么幅宽等于纸规
                    if(Convert.ToString(entity["FWidthRange"])!="" && Convert.ToString(entity["FWidthRange"])!=null)
                    {
                        subRow["FAuxPropertyId"] = entity["FWidthRange"]["F100001"]["FNumber"];
                        subRow["FAuxPropertyName"] = entity["FWidthRange"]["F100001"]["FDataValue"][0]["Value"];
                    }
                    else
                    {
                        subRow["FAuxPropertyId"] = Convert.ToInt32(entity["FGauge"]) / 10;
                    }
                    if(Convert.ToString(entity["FInDepositoryId"])!="")
                    {
                        //调入仓库编码
                        subRow["FInDepositoryId"] = entity["FInDepositoryId"]["Number"];
                        //调入仓库名称
                        subRow["FInDepositoryName"] = entity["FInDepositoryId"]["Name"][0]["Value"];
                    }
                   
                    //预计需求数量
                    subRow["FPlanDosage"] = entity["FPlanDosage"];
                    //实际领用量
                    subRow["FActuralDosage"] = entity["FActuralDosage"];
                    subTable.Rows.Add(subRow);
                }
                
                //单据体 机组 排序
                //DataTable copySubTable = subTable.Copy();
                DataView dv = subTable.DefaultView;
                dv.Sort = "FMachine";
                DataTable copySubTable = dv.ToTable();

                ds.Tables.Add(table);
                ds.Tables.Add(copySubTable);


                return ds;
            }
            return null;
        }
        
        /// <summary>
        /// 有源调拨单（不发布）保存
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="localid"></param>
        /// <param name="FPkValue">生产备料单主键</param>
        /// <param name="dataS">单据体</param>
        /// <param name="onlyMark">调用保存单据的唯一标识</param>
        /// <returns></returns>
        [WebMethod]
        public string SourceDirectTransfer(string accountId, string userid, string password, int localid, string FPkValue, DataSet dataS ,string onlyMark )
        {
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);
            PDADictionary<string, string> msg = new PDADictionary<string, string>();
            JObject obj = null;
            if (Login(client, accountId, userid, password, localid, out obj) == null || FPkValue == null || FPkValue == "" || dataS == null || dataS.Tables.Count == 0)
            {
                return null;
            }
            string userId = Convert.ToString(obj["Context"]["CurrentOrganizationInfo"]["ID"]);               //从obj直接获取用户Id

            DataTable table = dataS.Tables[0];
            System.Text.StringBuilder sbd = new System.Text.StringBuilder();
            sbd.Append("{\"Creator\":\"" + userId + "\",");
            sbd.Append("\"NeedUpDateFields\":[],");
            sbd.Append("\"IsDeleteEntry\":\"True\",");
            sbd.Append("\"SubSystemId\":\"\",");
            sbd.Append("\"IsVerifyBaseDataField\":\"false\",");
            sbd.Append("\"IsEntryBatchFill\":\"True\",");
            sbd.Append("\"Model\":{\"FID\":\"0\",");
            sbd.Append("\"FBillNo\":\"\",");
            sbd.Append("\"FModifierId\":{\"FUserID\":\"0\"},");
            sbd.Append("\"FModifyDate\":\"1900-01-01\",");
            sbd.Append("\"FCreatorId\":{\"FUserID\":\"0\"},");
            sbd.Append("\"FCreateDate\":\"1900-01-01\",");
            sbd.Append("\"FApproverId\":{\"FUserID\":\"0\"},");
            sbd.Append("\"FApproveDate\":\"1900-01-01\",");
            sbd.Append("\"FOrgId\":{\"FNumber\":\"\"},");
            sbd.Append("\"FPkValue\":\"" + FPkValue + "\",");
            sbd.Append("\"FEntity\":[");              //单据体
            int i = dataS.Tables[0].Rows.Count;
            foreach(DataRow dr in dataS.Tables[0].Rows)
            {
                i--;
                sbd.Append("{\"FEntryID\":\"0\",");
                sbd.Append("\"FEntryEntityPkvalues\":\""+dr["Id"]+"\",");
                sbd.Append("\"FBarCode\":\""+dr["FBarCode"] +"\",");
                sbd.Append("\"FMachine\":\"" + dr["FMachine"] + "\",");
                sbd.Append("\"FMaterialId\":{\"FNumber\":\""+dr["FMaterialId"] +"\"},");
                sbd.Append("\"FAuxPropId\":{\"FAUXPROPID__FF100001\":{\"FNumber\":\""+dr["FAuxPropId"] +"\"}},");
                sbd.Append("\"FBaseUnitId\":{\"FNumber\":\""+dr["UnitId"] +"\"},");
                sbd.Append("\"FBaseQty\":\""+dr["Qty"] +"\",");
                sbd.Append("\"FTargetFormId\":\"\"");
                sbd.Append("}");
                if (i > 0)
                    sbd.Append(",");
            }
            sbd.Append("]}}");
            // k7512ab6361f74e7fa3c056eede106a3d   有源调拨单（不发布） 唯一标识
            //string onlyMack = "k7512ab6361f74e7fa3c056eede106a3d";

            string resultSave = client.Save(onlyMark, sbd.ToString());          //保存
            //string resultSubmit = client.Submit("STK_TransferDirect", a1);               //提交
            //string resultAudit = client.Audit("STK_TransferDirect", a1);                 //审核
            JObject jo = (JObject)JsonConvert.DeserializeObject(resultSave);
            string isSuccess = jo["Result"]["ResponseStatus"]["IsSuccess"].ToString();
            if (isSuccess == "True")
            {
                return "保存成功";
            }
            string rs = Convert.ToString(jo["Result"]["ResponseStatus"]);
            if (rs != null && rs != "")
            {
                rs = Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"]);
                if (rs != null && rs != "")
                {
                    isSuccess += Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"][0]["FieldName"]);
                }
            }
            return "保存失败："+ isSuccess;
            
        }
        /// <summary>
        /// 生产备料到简单生产退料 中间单据 保存
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="localid"></param>
        /// <param name="FPkValue">生产备料单主键</param>
        /// <param name="dataS">单据体</param>
        /// <param name="onlyMark">调用保存单据的唯一标识</param>
        /// <returns></returns>
        [WebMethod]
        public string ReturnMtrlSerialSave(string accountId, string userid, string password, int localid, string FPkValue, DataSet dataS, string onlyMark)
        {
            FPkValue = "-1";
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);
            PDADictionary<string, string> msg = new PDADictionary<string, string>();
            JObject obj = null;
            if (Login(client, accountId, userid, password, localid, out obj) == null || FPkValue == null || FPkValue == "" || dataS == null || dataS.Tables.Count == 0)
            {
                return null;
            }
            string userId = Convert.ToString(obj["Context"]["CurrentOrganizationInfo"]["ID"]);               //从obj直接获取用户Id

            DataTable table = dataS.Tables[0];
            System.Text.StringBuilder sbd = new System.Text.StringBuilder();
            sbd.Append("{\"Creator\":\"" + userId + "\",");
            sbd.Append("\"NeedUpDateFields\":[],");
            sbd.Append("\"IsDeleteEntry\":\"True\",");
            sbd.Append("\"SubSystemId\":\"\",");
            sbd.Append("\"IsVerifyBaseDataField\":\"false\",");
            sbd.Append("\"IsEntryBatchFill\":\"True\",");
            sbd.Append("\"Model\":{\"FID\":\"0\",");
            sbd.Append("\"FBillNo\":\"\",");
            sbd.Append("\"FModifierId\":{\"FUserID\":\"0\"},");
            sbd.Append("\"FModifyDate\":\"1900-01-01\",");
            sbd.Append("\"FCreatorId\":{\"FUserID\":\"0\"},");
            sbd.Append("\"FCreateDate\":\"1900-01-01\",");
            sbd.Append("\"FApproverId\":{\"FUserID\":\"0\"},");
            sbd.Append("\"FApproveDate\":\"1900-01-01\",");
            sbd.Append("\"FOrgId\":{\"FNumber\":\"\"},");
            sbd.Append("\"FPkValue1\":\"" + FPkValue + "\",");
            sbd.Append("\"FEntity\":[");              //单据体
            int i = dataS.Tables[0].Rows.Count;
            foreach (DataRow dr in dataS.Tables[0].Rows)
            {
                i--;
                sbd.Append("{\"FEntryID\":\"0\",");
                sbd.Append("\"FEntryEntityPkvalues\":\"" + dr["Id"] + "\",");
                sbd.Append("\"FPkValue\":\"" + dr["FPkValue"] + "\",");
                sbd.Append("\"FBarCode\":\"" + dr["FBarCode"] + "\",");
                sbd.Append("\"FMachine\":\"" + dr["FMachine"] + "\",");
                sbd.Append("\"FMaterialId\":{\"FNumber\":\"" + dr["FMaterialId"] + "\"},");
                sbd.Append("\"FAuxPropId\":{\"FAUXPROPID__FF100001\":{\"FNumber\":\"" + dr["FAuxPropId"] + "\"}},");
                sbd.Append("\"FBaseUnitId\":{\"FNumber\":\"" + dr["UnitId"] + "\"},");
                sbd.Append("\"FBaseQty\":\"" + dr["Qty"] + "\",");
                sbd.Append("\"F_D_CountQty\":\"" + dr["FCountQty"] + "\",");
                sbd.Append("\"FTargetFormId\":\"\"");
                sbd.Append("}");
                if (i > 0)
                    sbd.Append(",");
            }
            sbd.Append("]}}");
            // k7512ab6361f74e7fa3c056eede106a3d   有源调拨单（不发布） 唯一标识
            //string onlyMack = "k7512ab6361f74e7fa3c056eede106a3d";

            string resultSave = client.Save(onlyMark, sbd.ToString());          //保存
            //string resultSubmit = client.Submit("STK_TransferDirect", a1);               //提交
            //string resultAudit = client.Audit("STK_TransferDirect", a1);                 //审核
            JObject jo = (JObject)JsonConvert.DeserializeObject(resultSave);
            string isSuccess = jo["Result"]["ResponseStatus"]["IsSuccess"].ToString();
            if (isSuccess == "True")
            {
                return "保存成功";
            }
            string rs = Convert.ToString(jo["Result"]["ResponseStatus"]);
            if (rs != null && rs != "")
            {
                rs = Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"]);
                if (rs != null && rs != "")
                {
                    isSuccess += Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"][0]["FieldName"]);
                }
            }
            return "保存失败：" + isSuccess;

        }
        /// <summary>
        /// 直接调拨单存入
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="localid"></param>
        /// <param name="bizType">调拨类型</param>
        /// <param name="outOrg">调出组织</param>
        /// <param name="outStock">调出仓库</param>
        /// <param name="inOrg">调入组织</param>
        /// <param name="inStock">调入仓库</param>
        /// <param name="dataS">条码信息</param>
        /// <returns></returns>
        /// PDADictionary<string, string>
        [WebMethod]
        public string SaveSTKTransferDirect(string accountId, string userid, string password, int localid,string bizType, string outOrg   ,string outStock   ,string inOrg  ,string inStock  ,DataSet dataS)
        {
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);
            PDADictionary<string, string> msg = new PDADictionary<string, string>();
            JObject obj = null;
            if (Login(client, accountId, userid, password, localid,out obj)==null)
            {
                return null;
            }

            //****************************************************************************************************************
            var billStr = client.View("STK_TransferDirect", "{\"CreateOrgId\":\"0\",\"Number\":\"ZJDB000063\",\"Id\":\"\"}");

            string userId = Convert.ToString( obj["Context"]["CurrentOrganizationInfo"]["ID"]) ;               //从obj直接获取用户Id
            //单据类型：FBillTypeID         单据类型  
            string FBillTypeID= "ZJDB08_SYS";

            //业务类型：FBizType            下拉
            string FBizType="0";

            //调拨方向：FTransferDirect     下拉
            string FTransferDirect="1";

             //调拨类型：FTransferBizType    下拉
            string FTransferBizType= bizType;

            //     调出库存组织：FStockOutOrgId      组织
            string FStockOutOrgId= outOrg; 
                                                           
            //调出货主类型：FOwnerTypeOutIdHead   多类别基础资料列表     ~~~~~~~~~~~~    
            string FOwnerTypeOutIdHead="BD_OwnerOrg";

            //     调入库存组织：FStockOrgId           组织
            string FStockOrgId= inOrg;

            //调入货主类型：FOwnerTypeIdHead      多类别基础资料列表  ~~~~~~~~~~~~~~~~~~~~~~
            string FOwnerTypeIdHead = "BD_OwnerOrg";

            //调入货主：FOwnerIdHead            多类别基础资料   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            string   FOwnerIdHead = inOrg;

            //日期：FDate             日期
            string FDate = DateTime.Now.ToString();

            //物料：FMaterialId          基础资料             
            //string FMaterialId ="0130018";

            //单位：FUnitID              计量单位
            string FUnitID="kg";

            //调拨数量：FQty              数量              
            string FQty =Convert.ToDecimal(1).ToString();

            //调出仓库：FSrcStockId       基础资料              （调出仓库 不等于 调入仓库）
            string FSrcStockId= outStock;

            //调入仓库：FDestStockId      基础资料              （调出仓库 不等于 调入仓库）
            string FDestStockId = inStock;


            //基本单位   FBaseUnitId
            string FBaseUnitId = FUnitID;

            //调拨数量（基本单位）     FBaseQty    基本单位数量   =   调拨数量
            string    FBaseQty = FQty;

            //调出货主:FOwnerOutIdHead          多类别基础资料     
            string FOwnerOutIdHead = "101";

            System.Text.StringBuilder sbd = new System.Text.StringBuilder();

            DataTable billTable = GetFBillEntry(dataS.Tables[0]);



            sbd.Append("{\"Creator\":\"" + userId);  //   4   
            sbd.Append("\",\"NeedUpDateFields\":[],");
            sbd.Append("\"NeedReturnFields\":[],");
            sbd.Append("\"IsDeleteEntry\":\"True\",");
            sbd.Append("\"SubSystemId\":\"\",");
            sbd.Append("\"IsVerifyBaseDataField\":\"false\",");
            sbd.Append("\"IsEntryBatchFill\":\"True\",");
            //");
            //sbd.Append("
            //自己虚拟两个物料和幅宽，数量，填入调拨单

            sbd.Append("\"Model\":");                    //3
            sbd.Append("{\"FID\":\"0\",");               //3
            sbd.Append("\"FBillNo\":\"\"");
            sbd.Append(",\"FBillTypeID\":{\"FNumber\":\""+ FBillTypeID + "\"},");      //单据类型：FBillTypeID         单据类型
            sbd.Append("\"FBizType\":\""+ FBizType + "\",");                        //业务类型：FBizType            下拉
            sbd.Append("\"FTransferDirect\":\""+ FTransferDirect + "\",");                 //调拨方向：FTransferDirect     下拉
            sbd.Append("\"FTransferBizType\":\""+ FTransferBizType + "\",");                //调拨类型：FTransferBizType    下拉
            sbd.Append("\"FSettleOrgId\":{\"FNumber\":\"\"},");
            sbd.Append("\"FSaleOrgId\":{\"FNumber\":\"\"},");
            sbd.Append("\"FStockOutOrgId\":{\"FNumber\":\""+ FStockOutOrgId + "\"},");    //调出库存组织：FStockOutOrgId     组织
            sbd.Append("\"FOwnerTypeOutIdHead\":\""+ FOwnerTypeOutIdHead + "\",");             //调出货主类型：FOwnerTypeOutIdHead   多类别基础资料列表
            sbd.Append("\"FOwnerOutIdHead\":{\"FNumber\":\""+ FOwnerOutIdHead + "\"},");                         //  调出货主:FOwnerOutIdHead          多类别基础资料  ~~~~~~~~~~~~~~~~~~
            sbd.Append("\"FStockOrgId\":{\"FNumber\":\""+ FStockOrgId + "\"},");       //调入库存组织：FStockOrgId           组织
            sbd.Append("\"FIsIncludedTax\":\"false\",");
            sbd.Append("\"FIsPriceExcludeTax\":\"false\",");
            sbd.Append("\"FOwnerTypeIdHead\":\""+ FOwnerTypeIdHead + "\",");                //调入货主类型：FOwnerTypeIdHead      多类别基础资料
            sbd.Append("\"FSETTLECURRID\":{\"FNumber\":\"\"},");
            sbd.Append("\"FOwnerIdHead\":{\"FNumber\":\""+ FOwnerIdHead + "\"},");                             //调入货主：FOwnerIdHead            多类别基础资料~~~~~~~~~
            sbd.Append("\"FStockerId\":{\"FNumber\":\"\"},");
            sbd.Append("\"FStockerGroupId\":{\"FNumber\":\"\"},");
            sbd.Append("\"FDate\":\""+ FDate + "\",");                //日期：FDate             日期
            sbd.Append("\"FNote\":\"\",");
            sbd.Append("\"FBaseCurrId\":{\"FNumber\":\"\"},");
            sbd.Append("\"FSUPPLIERID\":{\"FNumber\":\"\"},");
            //sbd.Append("\"FCustID\":{\"FNumber\":\"\"},");
            sbd.Append("\"FScanBox\":\"\",");
            sbd.Append("\"FThirdSystem\":\"\",");
            sbd.Append("\"FThirdSrcBillNo\":\"\",");
            sbd.Append("\"FThirdSrcId\":\"\",");
            sbd.Append("\"FBillEntry\":");                    //2        明细单据体：   FBillEntry      单据体
            sbd.Append("[");              //2
            int _i = 0;
            int _o = 0;
            string drM;
            string drA;
            decimal dec = 0;
            foreach(DataRow dr in billTable.Rows)
            {
                drM = Convert.ToString(dr["FMaterialId"]);
                drA = Convert.ToString(dr["FAuxPropId"]);
                sbd.Append("{\"FEntryID\":\""+ 0 + "\",");
                sbd.Append("\"FMaterialId\":{\"FNumber\":\"" + drM + "\"},");                  //物料：FMaterialId          基础资料
                sbd.Append("\"FAuxPropId\":{\"FAUXPROPID__FF100001\":{\"FNumber\":\""+ drA + "\"}},");                 //幅宽                  辅助属性
                sbd.Append("\"FUnitID\":{\"FNumber\":\"" + dr["FBaseUnitId"] + "\"},");                    //单位：FUnitID              计量单位
                sbd.Append("\"FSrcStockId\":{\"FNumber\":\"" + FSrcStockId + "\"},");            //调出仓库：FSrcStockId       基础资料              （调出仓库 不等于 调入仓库）
                sbd.Append("\"FDestStockId\":{\"FNumber\":\"" + FDestStockId + "\"},");          //调入仓库：FDestStockId      基础资料              （调出仓库 不等于 调入仓库）
                
                
                dec = 0;
                foreach (DataRow detailed in dataS.Tables[0].Rows)
                {
                    if (drM == Convert.ToString( detailed["FMaterialId"] ) && drA==Convert.ToString(detailed["FAuxPropId"]))
                    {
                        dec += Convert.ToDecimal(detailed["FBaseQty"]);
                    }
                }
                sbd.Append("\"FQty\":\"" + dec + "\"");                                        //调拨数量：FQty              数量
                #region  相关字段注释

                //                                                                                     //sbd.Append("\"FSrcStockLocId\":{},");
                //                                                                                     //sbd.Append("\"FLot\":{\"FNumber\":\"\"},");

                //                                                                                     //sbd.Append("\"FPrice\":\"0\",");

                //                                                                                     //sbd.Append("\"FDestStockLocId\":{},");
                //                                                                                     //sbd.Append("\"FBomId\":{\"FNumber\":\"\"},");
                //                                                                                     //sbd.Append("\"FSrcStockStatusId\":{\"FNumber\":\""+ FSrcStockStatusId + "\"},");    //调出库存状态：FSrcStockStatusId   基础资料
                //                                                                                     //sbd.Append("\"FDeliChkQualifyType\":\"\",");
                //                                                                                     //sbd.Append("\"FAmount\":\"0\",");
                //                                                                                     //sbd.Append("\"FProduceDate\":\"\",");
                //                                                                                     //sbd.Append("\"FDestStockStatusId\":{\"FNumber\":\""+ FDestStockStatusId + "\"},");   //调入库存状态：FDestStockStatusId   基础资料
                //                                                                                     //sbd.Append("\"FMtoNo\":\"\",");
                //                                                                                     //sbd.Append("\"FBusinessDate\":\"1900-01-01\",");
                //                                                                                     //sbd.Append("\"FExpiryDate\":\"\",");
                //                                                                                     //sbd.Append("\"FNoteEntry\":\"\",");
                //                                                                                     //sbd.Append("\"FProjectNo\":\"\",");
                //                                                                                     //sbd.Append("\"FOutJoinQty\":\"0\",");
                //                                                                                     //sbd.Append("\"FSecUnitId\":{\"FNumber\":\"\"},");
                //                                                                                     //sbd.Append("\"FSecQty\":\"0\",");                   
                //                                                                                     //sbd.Append("\"FBASEOUTJOINQTY\":\"0\",");
                //                                                                                     //sbd.Append("\"FBaseUnitId\":{\"FNumber\":\""+ FBaseUnitId + "\"},");                                                                //基本单位   FBaseUnitId
                //                                                                                     //sbd.Append("\"FExtAuxUnitId\":{\"FNumber\":\"\"},");
                //                                                                                     //sbd.Append("\"FExtAuxUnitQty\":\"0\",");
                //    sbd.Append("\"FBaseQty\":\"" + FBaseQty + "\",");                                                                //调拨数量（基本单位）     FBaseQty    基本单位数量
                //                                                                                                                     //sbd.Append("\"FOwnerTypeId\":\""+ FOwnerTypeId + "\",");                                                                           //调入货主类型(明细)      FOwnerTypeId       多类别基础资料列表
                //                                                                                                                     //sbd.Append("\"FOwnerId\":{\"FNumber\":\""+ FOwnerId + "\"},");                                                               //调入货主（明细）  FOwnerId    多类别基础资料
                //                                                                                                                     //sbd.Append("\"FOwnerTypeOutId\":\""+ FOwnerTypeOutId + "\",");                                                                          //调出货主类型(明细)        FOwnerTypeOutId       多类别基础资料列表
                //                                                                                                                     //sbd.Append("\"FISFREE\":\"false\",");
                //                                                                                                                     //sbd.Append("\"FOwnerOutId\":{\"FNumber\":\""+ FOwnerOutId + "\"},");                                              //调出货主（明细）      FOwnerOutId     多类别基础资料
                //                                                                                                                     //sbd.Append("\"FKeeperTypeId\":\""+ FKeeperTypeId + "\",");                                       //调入保管者类型     FKeeperTypeId     多类别基础资料列表
                //                                                                                                                     //sbd.Append("\"FActQty\":\"0\",");
                //                                                                                                                     //sbd.Append("\"FKeeperId\":{\"FNumber\":\""+ FKeeperId + "\"},");                             //调入保管者   FKeeperId            类别基础资料
                //                                                                                                                     //sbd.Append("\"FKeeperTypeOutId\":\""+ FKeeperTypeOutId + "\",");                                    //调出保管者类型  FKeeperTypeOutId     多类别基础资料列表
                //                                                                                                                     //sbd.Append("\"FKeeperOutId\":{\"FNumber\":\""+ FKeeperOutId + "\"},");                                           //调出保管者     FKeeperOutId       多类别基础资料
                //                                                                                                                     //sbd.Append("\"FDiscountRate\":\"0\",");  
                //                                                                                                                     //sbd.Append("\"FRepairQty\":\"0\",");
                //                                                                                                                     //sbd.Append("\"FRETURNNOTE\":\"\",");
                //                                                                                                                     //sbd.Append("\"FDestLot\":{\"FNumber\":\"\"},");
                //                                                                                                                     //sbd.Append("\"FDestMaterialId\":{\"FNumber\":\"\"},");
                //                                                                                                                     //sbd.Append("\"FDestBomId\":{\"FNumber\":\"\"},");
                //                                                                                                                     //sbd.Append("\"FServiceContext\":\"\",");
                //                                                                                                                     //sbd.Append("\"FPriceUnitID\":{\"FNumber\":\"\"},");
                //                                                                                                                     //sbd.Append("\"FPriceQty\":\"0\",");
                //                                                                                                                     //sbd.Append("\"FPriceBaseQty\":\"0\",");
                //                                                                                                                     //sbd.Append("\"FGrammage\":\"0\",");
                //                                                                                                                     //sbd.Append("\"FsalFLengthSo\":\"0\",");
                //                                                                                                                     //sbd.Append("\"FSOEntryId\":\"0\",");
                //                                                                                                                     //sbd.Append("\"FsalFWidthSo\":\"0\",");
                //                                                                                                                     //sbd.Append("\"FQmEntryId\":\"0\",");
                //                                                                                                                     //sbd.Append("\"FsalFHeightSo\":\"0\",");
                //                                                                                                                     //sbd.Append("\"FConvertEntryId\":\"0\",");
                //                                                                                                                     //sbd.Append("\"Fcustid1\":{\"FNumber\":\"\"},");
                //                                                                                                                     //sbd.Append("\"FThirdSrcEntryId\":\"\",");
                //                                                                                                                     //sbd.Append("\"FSerialSubEntity\":");       //
                //                                                                                                                     //sbd.Append("[{\"FDetailID\":\"0\",");      //1
                //                                                                                                                     //sbd.Append("\"FSerialNo\":\"\",");
                //                                                                                                                     //sbd.Append("\"FSerialNote\":\"\"}]");      //1

                #endregion

                sbd.Append("}");
                if (billTable.Rows.Count-1 > _i)
                    sbd.Append(",");
                _i++;
            }
            sbd.Append("],");
            sbd.Append("\"F_XSY_TD_BarCodeEntity\":");                    //5       条码明细：   FBillEntry      单据体
            sbd.Append("[");              //5
            _o = 0;
            foreach (DataRow detailed in dataS.Tables[0].Rows)
            {
                sbd.Append("{\"FDetailID\":\"" + 0 + "\",");
                sbd.Append("\"F_BCE_BarCode\":\"" + detailed["FBarCode"] + "\",");                                         //条码
                sbd.Append("\"F_BCE_MaterialId\":{\"FNumber\":\"" + detailed["FMaterialId"] + "\"},");                  //物料：FMaterialId
                sbd.Append("\"F_BCE_UnitID\":{\"FNumber\":\"" + detailed["FBaseUnitId"] + "\"},");                                //单位
                sbd.Append("\"F_BCE_AuxPropId\":{\"F_BCE_AuxPropId__FF100001\":{\"FNumber\":\"" + detailed["FAuxPropId"] + "\"}},");                 //幅宽   
                sbd.Append("\"F_BCE_OutStockId\":{\"FNumber\":\"" + FSrcStockId + "\"},");                                //调出仓库  
                sbd.Append("\"F_BCE_InStockId\":{\"FNumber\":\"" + FDestStockId + "\"},");                                //调入仓库  
                sbd.Append("\"F_BCE_Qty\":\"" + detailed["FBaseQty"] + "\"");                                                    //数量
                sbd.Append("}");
                if (dataS.Tables[0].Rows.Count - 1 > _o)
                    sbd.Append(",");
                _o++;
            }
            sbd.Append("]");                          
            sbd.Append("}");                           //3
            sbd.Append("}");                           //4
            string a = sbd.ToString();
            string orgId = outOrg;                    //使用组织，默认调查组织
            string messStr ="保存失败，提交失败，审核失败   ";
            string resultSave=   client.Save("STK_TransferDirect",sbd.ToString());          //保存
            JObject jo = (JObject)JsonConvert.DeserializeObject(resultSave);
            string isSuccess = jo["Result"]["ResponseStatus"]["IsSuccess"].ToString();
            if (isSuccess=="True")
            {
                
                messStr = "保存成功，提交失败，审核失败";
                string numbers = jo["Result"]["Number"].ToString();
                string a1 = "{\"CreateOrgId\":" + orgId + ",\"Numbers\":[\"" + numbers + "\"]}";
                string resultSubmit = client.Submit("STK_TransferDirect", a1);               //提交

                jo = (JObject)JsonConvert.DeserializeObject(resultSubmit);
                isSuccess= jo["Result"]["ResponseStatus"]["IsSuccess"].ToString();
                if(isSuccess=="True")
                {
                    messStr = "保存成功，提交成功，审核失败";

                    string resultAudit = client.Audit("STK_TransferDirect", a1);                 //审核
                    //return resultAudit;
                    jo = (JObject)JsonConvert.DeserializeObject(resultAudit);
                    isSuccess = jo["Result"]["ResponseStatus"]["IsSuccess"].ToString();
                    if(isSuccess=="True") messStr = "保存成功，提交成功，审核成功";
                }
                //return resultSubmit;
            }
            if(isSuccess=="False")
            {
                string rs = Convert.ToString(jo["Result"]["ResponseStatus"]);
                if (rs != null && rs != "")
                {
                    rs = Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"]);
                    if (rs != null && rs != "")
                    {
                        messStr += Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"][0]["Message"]);
                    }
                }
            }

            return messStr;

        }
        /// <summary>
        /// 创建单据体
        /// </summary>
        /// <param name="table">子单据体</param>
        /// <returns></returns>
        public DataTable GetFBillEntry(DataTable table)
        {
            DataTable FBillEntry =table.Clone();
            bool _bool = true;
            string mNum;
            string apNum;
            foreach (DataRow dr in table.Rows)
            {
                _bool = true;
                mNum = Convert.ToString(dr["FMaterialId"]);
                apNum = Convert.ToString(dr["FAuxPropId"]);
                foreach (DataRow fb in FBillEntry.Rows)
                {
                    if (mNum==Convert.ToString(fb["FMaterialId"]) && apNum==Convert.ToString(fb["FAuxPropId"]))
                    {
                        _bool = false;
                    }
                }
                if (_bool)
                {
                    DataRow row = FBillEntry.NewRow();
                    row["FMaterialId"] = dr["FMaterialId"];
                    row["FBarCode"] = dr["FBarCode"];
                    row["FBaseUnitId"] = dr["FBaseUnitId"];
                    row["FAuxPropId"] = dr["FAuxPropId"];
                    FBillEntry.Rows.Add(row);
                }
            }
            return FBillEntry;
        }

        /// <summary>
        /// 根据组织，仓库获取 盘点作业单
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="localid"></param>
        /// <param name="org">组织Id</param>
        /// <param name="stk">仓库Id</param>
        /// <returns></returns>
        [WebMethod]
        public DataSet GetInventoryBill(string accountId, string userid, string password, int localid, string orgId, string stkId)
        {
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);
            PDADictionary<string, string> msg = new PDADictionary<string, string>();
            JObject obj;
            if (Login(client, accountId, userid, password, localid, out obj) == null)
            {
                return null;
            }
            //盘点作业单 
            //FormId 表单标识
            //FieldKeys 要获取的字段的标识 用,隔开
            //FilterString 过滤字符串 
            DateTime now = DateTime.Now;
            string formId = "STK_StockCountInput";
            //                   单据编号  账存日期  备注             
            string fieldKeys = "FBillNo,FBackUpDate,FNoteHead,FID";
            string filter = string.Format(
                "(FDocumentStatus='d'or FDocumentStatus='a') and FStockId='{0}' and FBackUpDate <= '{1}' and FBackUpDate>{2} and FStockOrgId={3}  and FIsBoolBasePaper='1' ",
                stkId, now, now.AddMonths(2), orgId
                );
            //filter = null;
            string str = string.Format(
                "\"FormId\":\"{0}\",\"FieldKeys\":\"{1}\",\"FilterString\":\"{2}\",\"OrderString\":\"FBackUpDate DESC\",\"TopRowCount\":\"0\",\"StartRow\":\"0\",\"Limit\":\"1999\"",
                formId, fieldKeys, filter
                );
            List<List<object>> datas = client.ExecuteBillQuery("{" + str + "}");
            if (datas.Count == 0 || datas == null) return null;
            Type type = typeof(string);
            DataSet set = new DataSet();
            DataTable table = new DataTable();
            table.Columns.Add("FBillNo", type);
            table.Columns.Add("FBackUpDate", type);
            table.Columns.Add("FNoteHead", type);
            table.Columns.Add("ID", type);
            bool _bool = true;
            foreach (var data in datas)
            {
                _bool = true;
                string bill = Convert.ToString(data[0]);
                foreach(DataRow row in table.Rows)
                {
                    if (Convert.ToString(row["FBillNo"]) == bill)
                        _bool= false;
                }
                if(_bool)
                {
                    DataRow dr = table.NewRow();
                    dr["FBillNo"] = Convert.ToString(data[0]);                 //单据编号
                    dr["FBackUpDate"] = Convert.ToString(Convert.ToDateTime(data[1]).ToString("yyyy-MM-dd"));             //账存日期
                    dr["FNoteHead"] = Convert.ToString(data[2]);               //备注
                    dr["ID"] = Convert.ToString(data[3]);                     //单据Id
                    table.Rows.Add(dr);
                }
                
            }

            set.Tables.Add(table);
            return set;
        }
        /// <summary>
        /// 物料盘点保存
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="localid"></param>
        /// <param name="fid">单据Id</param>
        /// <param name="dataSet">单据体</param>
        /// <returns></returns>
        [WebMethod]
        public string InventorySave(string accountId, string userid, string password, int localid, string id,DataSet dataSet)
        {
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);

            JObject obj;
            if (Login(client, accountId, userid, password, localid, out obj) == null)
            {
                return null;
            }
            var billStr = client.View("STK_StockCountInput", "{\"CreateOrgId\":\"0\",\"Number\":\"PDZY000001\",\"Id\":\"\"}");
            //JObject jo = (JObject)JsonConvert.DeserializeObject(billStr);
            string userId = Convert.ToString(obj["Context"]["CurrentOrganizationInfo"]["ID"]);               //从obj直接获取用户Id
            DataTable table = dataSet.Tables[0];
            string _id = id;                //单据Id
            DataTable detailedTable = dataSet.Tables[1];


            System.Text.StringBuilder sbd = new System.Text.StringBuilder();
            sbd.Append("{\"Creator\":\""+ userId+ "\",");
            //                                     物料          单位        账存数            幅宽         盘点数        单据体      库存状态            子单据体        编码               物料              单位          账存         盘点数            幅宽
            sbd.Append("\"NeedUpDateFields\":[\"FMaterialId\",\"FUnitID\",\"FAcctQty\",\"FAuxpropId\",\"FCountQty\",\"FBillEntry\",\"FStockStatusId\",\"F_XSY_Detailed\",\"F_D_BarCode\",\"F_D_MaterialId\",\"F_D_UnitID\",\"F_D_Qty\",\"F_D_CountQty\",\"F_D_AuxpropId\"],");
            sbd.Append("\"NeedReturnFields\":[\"FMaterialId\",\"FUnitID\",\"FAcctQty\",\"FAuxpropId\",\"FCountQty\"],");
            sbd.Append("\"IsDeleteEntry\":\"True\",");
            sbd.Append("\"SubSystemId\":\"\",");
            sbd.Append("\"IsVerifyBaseDataField\":\"false\",");
            sbd.Append("\"IsEntryBatchFill\":\"True\",");
            sbd.Append("\"Model\":{");
            sbd.Append("\"FID\":\""+_id+"\",");
            //\"FBillTypeID\":{\"FNumber\":\"\"},
            //\"FStockOrgId\":{\"FNumber\":\"\"},
            //sbd.Append("\"FNoteHead\":\"555555\",");
            //\"FDate\":\"1900-01-01\",
            //\"FSource\":\"\",
            sbd.Append("\"FBillEntry\":[");
            string entryId;
            int _i = 0;
            int _iEnt = 0;
            string str;
            decimal decSum = 0;
            string mateNum;
            string auxNum;
            foreach (DataRow dr in table.Rows)
            {
                entryId = Convert.ToString(dr["ID"]);
                sbd.Append("{\"FEntryID\":\"" + entryId + "\",");
                mateNum = Convert.ToString(dr["FMaterialNum"]);                 //物料编码
                auxNum = Convert.ToString(dr["AuxpropNum"]);                   //幅宽
                if (entryId=="0")
                {
                    sbd.Append("\"FAuxpropId\":{\"FAUXPROPID__FF100001\":{\"FNumber\":\"" + auxNum + "\"}},");
                    sbd.Append("\"FMaterialId\":{\"FNumber\":\"" + mateNum + "\"},");
                    //sbd.Append("\"FAcctQty\":\"" + dr["FAcctQty"] + "\",");                                              //账存数
                    sbd.Append("\"FUnitID\":{\"FNumber\":\"" + dr["FUnit"] + "\"},");                                     //单位
                    sbd.Append("\"FStockStatusId\":{\"FNumber\":\"KCZT01_SYS\"},");                                        //库存状态
                    sbd.Append("\"F_XSY_Detailed\":[");                                                                    //子单据体
                    _iEnt = 0;
                    foreach (DataRow xDr in detailedTable.Rows)
                    {
                        if (mateNum == Convert.ToString(xDr["FMaterialNum"]) && auxNum == Convert.ToString(xDr["AuxpropNum"]))
                        {
                            decSum += Convert.ToDecimal(xDr["F_D_CountQty"] ?? 0);
                            str = JsonEntry(xDr);
                            sbd.Append(JsonEntry(xDr));
                            if (detailedTable.Rows.Count - 1 > _iEnt)
                                sbd.Append(",");
                        }
                        _iEnt++;

                    }
                    sbd.Append("],");
                }
                else
                {
                    sbd.Append("\"F_XSY_Detailed\":[");
                    _iEnt = 0;
                    foreach (DataRow xDr in detailedTable.Rows)
                    {
                        if(mateNum == Convert.ToString(xDr["FMaterialNum"]) && auxNum == Convert.ToString(xDr["AuxpropNum"]))
                        {
                            decSum += Convert.ToDecimal(xDr["F_D_CountQty"] ?? 0);
                            str = JsonEntry(xDr);
                            sbd.Append(JsonEntry(xDr));
                            if (detailedTable.Rows.Count - 1 > _iEnt)
                                sbd.Append(",");
                        }
                        
                        _iEnt++;
                    }
                    sbd.Append("],");
                }
                sbd.Append("\"FCountQty\":\"" + decSum + "\"");               //单据体盘点数
                decSum = 0;
                sbd.Append("}");

                if (table.Rows.Count - 1 > _i)
                    sbd.Append(",");
                _i++;
            }

            #region 字符串备注
            //sbd.Append("\"FStockId\":{\"FNumber\":\"CK003\"},");                 //仓库编码
            //\"FStockLocId\":{},
            //\"FMaterialId\":{\"FNumber\":\"\"},
            //\"FStockStatusId\":{\"FNumber\":\"\"},
            //\"FExtAuxUnitId\":{\"FNumber\":\"\"},
            //\"FAuxpropId\":{\"FAUXPROPID__FF100001\":{\"FNumber\":\"\"}},
            //\"FLot\":{\"FNumber\":\"\"},
            //\"FUnitID\":{\"FNumber\":\"\"},
            //\"FCountQty\":\"0\",
            //\"FOwnerTypeId\":\"\",
            //\"FNote\":\"\",
            //\"FOwnerId\":{\"FNumber\":\"\"},
            //\"FKeeperTypeId\":\"\",
            //\"FKeeperId\":{\"FNumber\":\"\"},
            //\"FBomId\":{\"FNumber\":\"\"},
            //\"FMtoNo\":\"\",
            //\"FProduceDate\":\"1900-01-01\",
            //\"FExpiryDate\":\"1900-01-01\",
            //\"FExtAuxUnitQty\":\"0\",
            //\"FGainBillTypeId\":{\"FNumber\":\"\"},
            //\"FLossBillTypeId\":{\"FNumber\":\"\"},
            //\"FGrammage\":\"0\",
            //\"FsalFLengthSo\":\"0\",
            //\"FsalFWidthSo\":\"0\",
            //\"FsalFHeightSo\":\"0\",
            //\"Fcustid1\":{\"FNumber\":\"\"},
            //\"FEntrySerial\":[{\"FDetailID\":\"0\",\"FSerialNo\":\"\",\"FStatus\":\"false\",\"FSNNote\":\"\"}]
            //sbd.Append("},");
            //sbd.Append("{\"FEntryID\":\"100005\"},");
            //sbd.Append("{\"FEntryID\":\"100006\"},");
            //sbd.Append("{\"FEntryID\":\"0\",\"FBarCode\":\"dddd\",\"FStockId\":{\"FNumber\":\"CK001\"},\"FMaterialId\":{\"FNumber\":\"0130018\"},\"FStockStatusId\":{\"FNumber\":\"KCZT01_SYS\"}}");
            #endregion

            sbd.Append("]");
            sbd.Append("}}");
            string a = sbd.ToString();
            string resultSave = client.Save("STK_StockCountInput", sbd.ToString());          //保存
            JObject jo = (JObject)JsonConvert.DeserializeObject(resultSave);
            string isSuccess = jo["Result"]["ResponseStatus"]["IsSuccess"].ToString();
            if (isSuccess == "True")
            {
                return "保存成功";
            }
            string rs = Convert.ToString(jo["Result"]["ResponseStatus"]);
            if (rs != null && rs != "")
            {
                rs = Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"]);
                if (rs != null && rs != "")
                {
                    isSuccess += Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"][0]["FieldName"]);
                }
            }
            return "保存失败"+ isSuccess;
        }
        /// <summary>
        /// 物料盘点 子单据体Json
        /// </summary>
        /// <param name="xDr">子单据体行</param>
        /// <returns>添加String 或 修改String</returns>
        public string JsonEntry(DataRow xDr)
        {
            string entryId = Convert.ToString(xDr["ID"]);
            System.Text.StringBuilder sbd = new System.Text.StringBuilder();
            sbd.Append("{\"FDetailID\":\"" + xDr["ID"] + "\",");
            if (entryId == "0")
            {
                sbd.Append("\"F_D_BarCode\":\"" + xDr["F_D_BarCode"] + "\",");
                sbd.Append("\"F_D_MaterialId\":{\"FNumber\":\"" + xDr["FMaterialNum"] + "\"},");                          //物料编码
                sbd.Append("\"F_D_AuxpropId\":{\"F_D_AuxpropId__FF100001\":{\"FNumber\":\"" + xDr["AuxpropNum"] + "\"}},");     //幅宽
                sbd.Append("\"F_D_UnitID\":{\"FNumber\":\"" + xDr["F_D_UnitID"] + "\"},");                                     //单位
                sbd.Append("\"F_D_Qty\":\"" + xDr["F_D_Qty"] + "\",");                                        //账存数
                sbd.Append("\"F_D_CountQty\":\"" + xDr["F_D_CountQty"] + "\"}");                              //盘点数
            }
            else
            {

                sbd.Append("\"F_D_CountQty\":\"" + xDr["F_D_CountQty"] + "\"}");
            }
            return Convert.ToString(sbd);
        }
        /// <summary>
        /// 物料盘点-单据信息
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="localid"></param>
        /// <param name="number">单据编号</param>
        /// <returns></returns>
        [WebMethod]
        public DataSet InquiryBillNo(string accountId, string userid, string password, int localid,string number)
        {
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);

            JObject obj;
            if (Login(client, accountId, userid, password, localid, out obj) == null)
            {
                return null;
            }

            string billName = "STK_StockCountInput";      //单据名
            var billStr=client.View(billName, "{\"CreateOrgId\":\"0\",\"Number\":\""+number+"\",\"Id\":\"\"}");
            JObject jo = (JObject)JsonConvert.DeserializeObject(billStr);
            //var aaa=client.ExecuteBillQuery("{\"FormId\":\""+ billName + "\",\"FieldKeys\":\"\",\"FilterString\":\"\",\"OrderString\":\"\",\"TopRowCount\":\"0\",\"StartRow\":\"0\",\"Limit\":\"0\"}");
            string str =Convert.ToString( jo["Result"]["ResponseStatus"]);
            if (str == "" || str == null)
            {
                string schemeName = Convert.ToString(jo["Result"]["Result"]["SchemeName"]);
                string status =  Convert.ToString( jo["Result"]["Result"]["DocumentStatus"]);
                if (status == "D" || status == "A")
                {
                    string auxprop = null;
                    Type type = typeof(string);
                    DataSet ds = new DataSet();
                    DataTable table = new DataTable();
                    table.Columns.Add("ID", type);                    //Id
                    //table.Columns.Add("FBarCode", type);              //条码
                    table.Columns.Add("FMaterialName", type);         //物料名称
                    table.Columns.Add("FMaterialNum", type);          //物料编码
                    table.Columns.Add("FAcctQty", type);              //账存数
                    table.Columns.Add("AuxpropNum", type);             //幅宽
                    table.Columns.Add("AuxpropValue", type);           //幅宽值
                    table.Columns.Add("FDiameter", type);             //芯径  
                    table.Columns.Add("FDensity", type);              //密度
                    table.Columns.Add("FUnit", type);                  //单位  
                    table.Columns.Add("FCountQty", type);            //盘点数

                    //子单据体
                    DataTable subTable = new DataTable();
                    subTable.Columns.Add("ID", type);                  //单据Id
                    subTable.Columns.Add("FID", type);                 //父类Id
                    subTable.Columns.Add("F_D_BarCode", type);        //条码
                    subTable.Columns.Add("FMaterialName", type);         //物料名称    
                    subTable.Columns.Add("FMaterialNum", type);          //物料编码    
                    subTable.Columns.Add("AuxpropNum", type);             //幅宽       
                    subTable.Columns.Add("AuxpropValue", type);           //幅宽值
                    subTable.Columns.Add("FDiameter", type);             //芯径  
                    subTable.Columns.Add("FDensity", type);              //密度
                    subTable.Columns.Add("F_D_UnitID", type);          //单位         
                    subTable.Columns.Add("F_D_Qty", type);             //账存数
                    subTable.Columns.Add("F_D_CountQty", type);        //盘点数

                    foreach (var o in jo["Result"]["Result"]["StkCountInputEntry"])
                    {
                        DataRow dr = table.NewRow();
                        dr["ID"] = o["Id"];
                        //dr["FBarCode"] = o["FBarCode"];                                                         //条码
                        dr["FMaterialNum"] = o["MaterialId"]["Number"];                                         //物料编码
                        dr["FMaterialName"] = o["MaterialId"]["MultiLanguageText"][0]["Name"];                  //物料名
                        dr["FAcctQty"] = o["AcctQty"];                                                          //账存数
                        dr["FCountQty"] = o["CountQty"];
                        auxprop = Convert.ToString(o["AuxpropId"]);
                        if (auxprop != null && auxprop != "")
                        {
                            dr["AuxpropValue"] = o["AuxpropId"]["F100001"]["MultiLanguageText"][0]["FDataValue"];      //幅宽
                            dr["AuxpropNum"] = o["AuxpropId"]["F100001"]["FNumber"];
                        }
                        dr["FDiameter"] = Convert.ToString(FDiameter());                                       //芯径                              
                        dr["FUnit"] = o["UnitID"]["Number"];                                                   //单位
                        dr["FDensity"] = o["MaterialId"]["Raw_Material"][0]["FDensity"];                       //密度
                        foreach (var z in o["F_XSY_Detailed"])
                        {
                            DataRow zDr = subTable.NewRow();
                            zDr["ID"] = z["Id"];
                            zDr["FID"] = o["Id"];                                                                      //父类Id
                            zDr["F_D_BarCode"] = z["F_D_BarCode"];
                            zDr["F_D_UnitID"] = z["F_D_UnitID"];
                            zDr["F_D_Qty"] = z["F_D_Qty"];
                            zDr["F_D_CountQty"] = z["F_D_CountQty"];
                            zDr["FMaterialNum"] = z["F_D_MaterialId"]["Number"];                                         //物料编码 
                            zDr["FMaterialName"] = z["F_D_MaterialId"]["MultiLanguageText"][0]["Name"];                  //物料名  
                            zDr["FDiameter"] = Convert.ToString(FDiameter());                                             //芯径
                            zDr["FDensity"] = z["F_D_MaterialId"]["Raw_Material"][0]["FDensity"];                         //密度
                            auxprop = Convert.ToString(z["F_D_AuxpropId"]);
                            if (auxprop != null && auxprop != "")
                            {
                                zDr["AuxpropValue"] = z["F_D_AuxpropId"]["F100001"]["MultiLanguageText"][0]["FDataValue"];      //幅宽  
                                zDr["AuxpropNum"] = z["F_D_AuxpropId"]["F100001"]["FNumber"];
                            }
                            subTable.Rows.Add(zDr);
                        }
                        table.Rows.Add(dr);
                    }
                    ds.Tables.Add(table);
                    ds.Tables.Add(subTable);          
                    return ds;
                }
            }
            return null;

        }


        /// <summary>
        /// 生产备料单保存
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="userid"></param>
        /// <param name="password"></param>
        /// <param name="localid"></param>
        /// <param name="id"></param>
        /// <param name="dataSet"></param>
        /// <returns></returns>
        [WebMethod]
        public string ProductionStockSave(string accountId, string userid, string password, int localid, string id, DataSet dataSet)
        {
            K3CloudApiClient client = new K3CloudApiClient(ConfigDatas.K3ServerUrl);

            JObject obj;
            if (Login(client, accountId, userid, password, localid, out obj) == null)
            {
                return null;
            }
            var billStr = client.View("UN_ManufactureStock", "{\"CreateOrgId\":\"0\",\"Number\":\"SCBL18021\",\"Id\":\"\"}");
            //JObject jo = (JObject)JsonConvert.DeserializeObject(billStr);
            string userId = Convert.ToString(obj["Context"]["CurrentOrganizationInfo"]["ID"]);               //从obj直接获取用户Id
            DataTable table = dataSet.Tables[0];                  //单据体

            DataTable detailedTable = dataSet.Tables[1];          //子单据体 
            System.Text.StringBuilder sbd = new System.Text.StringBuilder();

            sbd.Append("{\"Creator\":\""+ userId + "\","); 
            //                                  单据体        所需物料          调出仓库               幅宽            实际领用量        子单据体         子单据体物料  子单据体调入仓库    数量        幅宽          单位       条码
            sbd.Append("\"NeedUpDateFields\":[\"FEntity\",\"FRawMaterialId\",\"FOutDepository\",\"FExpectRangeWidth\",\"FActualQty\",\"F_UN_SubEntity\",\"FMaterialId\",\"FInWarehouse\",  \"FQty\", \"FRangeWidth\",\"FUnit\",\"FBarCode\" ],");

            sbd.Append("\"NeedReturnFields\":[],");

            sbd.Append("\"IsDeleteEntry\":\"True\",");

            sbd.Append("\"SubSystemId\":\"\",");

            sbd.Append("\"IsVerifyBaseDataField\":\"false\",");

            sbd.Append("\"IsEntryBatchFill\":\"True\",");

            sbd.Append("\"Model\":{\"FID\":\""+id+"\",");

            sbd.Append("\"FOutDepository\":{\"FNumber\":\"\"},");              //调出仓库                        ******************

            sbd.Append("\"FEntity\":[");                                       //单据体

            int i = 0;
            int iEnt = 0;
            string entryId;
            decimal sum = 0;
            foreach (DataRow dr in table.Rows)
            {
                entryId = Convert.ToString(dr["ID"]);
                sbd.Append("{\"FEntryID\":\""+ entryId + "\",");                                //单据Id
                if (entryId=="0")
                {
                   // sbd.Append("\"FOrderNo\":\"\",");                                  //生产单号           ***********************************

                    sbd.Append("\"FRawMaterialId\":{\"FNumber\":\""+dr["FMaterialNum"] +"\"},");              //物料

                    sbd.Append("\"FExpectRangeWidth\":{\"FEXPECTRANGEWIDTH__FF100001\":{\"FNumber\":\""+dr["AuxpropNum"] +"\"}},");   //幅宽

                    

                    sbd.Append("\"F_UN_SubEntity\":[");                                 //子单据体

                    iEnt = 0;
                    sum = 0;
                    foreach (DataRow xDr in detailedTable.Rows)
                    {
                        
                    }
                    sbd.Append("],");
                    sbd.Append("\"FActualQty\":\"0\"");                                //实际领用数量
                    sbd.Append("}");
                }
                else
                {

                }
                
                if (table.Rows.Count - 1 > i)
                    sbd.Append(",");
                i++;

            }


            sbd.Append("]");

            sbd.Append("}}");

            
            try
            {
                string a = sbd.ToString();
                string resultSave = client.Save("STK_StockCountInput", sbd.ToString());          //保存
                JObject jo = (JObject)JsonConvert.DeserializeObject(resultSave);
                string isSuccess = jo["Result"]["ResponseStatus"]["IsSuccess"].ToString();
                if (isSuccess == "True")
                {
                    return "保存成功";
                }
                string rs = Convert.ToString(jo["Result"]["ResponseStatus"]);
                if (rs != null && rs != "")
                {
                    rs = Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"]);
                    if (rs != null && rs != "")
                    {
                        isSuccess += Convert.ToString(jo["Result"]["ResponseStatus"]["Errors"][0]["FieldName"]);
                    }
                }
                return "保存失败"+isSuccess;
            }
            catch
            {
                return "报错：保存失败";
            }
        }
        /// <summary>
        /// 备料单 子单据体Json
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        public string JsonPS(DataRow dr)
        {
            string entryId = Convert.ToString(dr["ID"]);
            System.Text.StringBuilder sbd = new System.Text.StringBuilder();
            sbd.Append("{\"FDetailID\":\"" + dr["ID"] + "\",");
            sbd.Append("\"FMaterialId\":{\"FNumber\":\"" + dr["FMaterialNum"] + "\"},");                  //物料

            sbd.Append("\"FQty\":\"" + dr["F_D_Qty"] + "\",");                                          //数量

            sbd.Append("\"FRangeWidth\":{\"FRANGEWIDTH__FF100001\":{\"FNumber\":\"" + dr["AuxpropNum"] + "\"}},");           //幅宽

            sbd.Append("\"FUnit\":{\"FNumber\":\"" + dr["F_D_UnitID"] + "\"},");                         //单位

            sbd.Append("\"FBarCode\":\"" + dr["F_D_BarCode"] + "\",");                                    //条码

            sbd.Append("\"FInWarehouse\":{\"FNumber\":\"" + dr["inStock"] + "\"}}");                  //调入仓库

            return Convert.ToString(sbd);
        }
    }

}
